import { fetchEventSource } from '@microsoft/fetch-event-source';

export function customStream(user, question, onMessage, onClose, onError, aiMessageIndex) {
    const abortController = new AbortController();
    const url = new URL('/dev-api/ai/chat/stream', window.location.origin);

    // 从 Cookie 中获取名为 'Admin-Token' 的值
    const getAdminTokenFromCookie = () => {
        const cookieParts = document.cookie.split('; ');
        for (const part of cookieParts) {
            const separatorIndex = part.indexOf('=');
            if (separatorIndex === -1) continue;

            const key = part.substring(0, separatorIndex);
            const value = part.substring(separatorIndex + 1);

            if (key === 'Admin-Token') {
                return decodeURIComponent(value);
            }
        }
        return null;
    };

    // 获取 Cookie 中的 Admin-Token
    const adminToken = getAdminTokenFromCookie();

    // 调试信息
    if (adminToken) {
        console.debug('从 Cookie 中获取到 Admin-Token');
    } else {
        console.warn('未找到名为 "Admin-Token" 的 Cookie');
    }

    const formData = new URLSearchParams();
    formData.append('user', String(user || 'unknown'));
    formData.append('question', String(question || ''));

    // 构建请求头
    const headers = {
        'Accept': 'text/event-stream',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cache-Control': 'no-cache',
    };
    // 若存在 Admin-Token，拼接为 Bearer 格式的 Authorization 头
    if (adminToken) {
        headers['Authorization'] = `Bearer ${adminToken}`;
    }

    fetchEventSource(url.toString(), {
        method: 'POST',
        headers,
        body: formData.toString(),
        signal: abortController.signal,
        mode: 'cors',
        credentials: 'include',

        async onopen(response) {
            console.debug('接口响应状态：', response.status);

            if (response.status === 401) {
                const errorMsg = adminToken
                    ? '登录已过期，请重新登录'
                    : '未检测到 Admin-Token 信息，请先登录';
                onError?.(new Error(errorMsg));
                abortController.abort();
                return;
            }

            if (response.ok && response.headers.get('content-type')?.includes('text/event-stream')) {
                return;
            } else {
                let errorData;
                try {
                    errorData = await response.json();
                } catch {
                    errorData = { msg: await response.text() || '接口响应异常' };
                }
                onError?.(new Error(errorData.msg || '接口返回格式错误'));
                abortController.abort();
            }
        },
        onmessage(event) {
            if (event.data) {
                const content = event.data.startsWith('data:')
                    ? event.data.slice(5).trim()
                    : event.data;
                onMessage?.(content, aiMessageIndex);
            }
        },
        onclose() {
            console.debug('SSE 连接已关闭');
            onClose?.();
        },
        onerror(error) {
            console.error('SSE 错误：', error);
            onError?.(new Error(`连接错误：${error.message || '未知错误'}`));
        }
    });

    return abortController;
}